const db = uniCloud.database()
const createConfig = require('uni-config-center')
const {
	Decrypt
} = require('../utils/script.js')
const collectionName = "uni-id-users"
const uniIdConfig = createConfig({
	pluginId: 'uni-id'
}).config()
let uniID = require('uni-id')


/**
 * 获取code2Session
 * @param {Object} platform
 * @param {Object} code
 */
// 通过appid 和 AppSecret 获取token 
async function code2Session({
	platform,
	code,
	detail
}) {
	const code2SessionUrl = {
		'mp-qq': 'https://api.q.qq.com/sns/jscode2session?&grant_type=authorization_code'
	}
	let res = {}
	// 通过appid 和 scret 获取微信服务器会话session_key
	const apiUrl =
		`${code2SessionUrl[platform]}&appid=${uniIdConfig[platform].oauth.qq.appid}&secret=${uniIdConfig[platform].oauth.qq.appsecret}&js_code=${code}`

	// 获取会话
	const session = await uniCloud.httpclient.request(apiUrl, {
		method: 'POST',
		data: {},
		dataType: 'json'
	})
	if (!session.data) return {
		code: 0,
		data: '请求错误'
	}
	let {
		openid,
		session_key
	} = session.data
	res.session_key = session_key
	// 解密用户信息
	let userInfo = Decrypt({
		session_key,
		...detail
	})
	// 查询数据库是否存在改用户，如果不存在 则创建一个用户--通过appid进行查询
	// 注册信息使用 username:appid password:appid
	let from=platform.split("-")[1]
	let queryName=`${from}_openid.${platform}`
	let eqPlatform=`${from}_openid`
	const cloudUser = await db.collection(collectionName).where({
		[eqPlatform]: {
			[platform]:openid
		}
	}).get()
	if (!cloudUser.data.length) {
		// uniID.regi 注册并更新用户信息
		res = await uniID.register({
			username: userInfo.openId,
			password: userInfo.openId,
			nickname: userInfo.nickName,
			avatar:userInfo.avatarUrl,
			inviteCode: 0
		});
		// 更新用户信息
		let headimgurlFile = {},
			cloudPath = res.uid + '/' + Date.now() + "headimgurl.jpg";
		let getImgBuffer = await uniCloud.httpclient.request(userInfo.avatarUrl)
		if (getImgBuffer.status == 200) {
			let {
				fileID
			} = await uniCloud.uploadFile({
				cloudPath,
			 fileContent: getImgBuffer.data
			});
			headimgurlFile = {
				name: cloudPath,
				extname: "jpg",
				url: fileID
			}
		}
		await uniID.updateUser({
			uid: res.uid,
			avatar_file: headimgurlFile,
			[queryName]:openid
		})
		res.userInfo.avatar_file = headimgurlFile;
		res.type = 'register'
	} {
		res.userInfo = userInfo
		res.type = 'login'
	}
	return res
}

module.exports = {
	code2Session
}
